import {messages} from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute'
import { message, Button, Popconfirm, Icon, Form, Input, Switch, Row, Col, Radio, TimePicker } from 'antd';
import ResizeTable from 'components/resize-table'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
import moment from 'moment';
import Searcher from 'components/searcher'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'

class NewScene extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      durationType: 1, //可用时段类型
      startTime: moment('00:00', 'HH:mm'),
      endTime: moment('23:59', 'HH:mm'),
      visibleForms: [] //适用表单列表，为空表示通用
    };
  }

  componentDidMount() {};

  componentWillReceiveProps(nextProps) {
    const { showSlideFrame, form } = this.props;
    if (!showSlideFrame && nextProps.showSlideFrame) {
      if (nextProps.record) {
        this.setState({
          durationType: nextProps.record.durationType,
          startTime: moment(nextProps.record.startTime, 'HH:mm'),
          endTime: moment(nextProps.record.endTime, 'HH:mm'),
          visibleForms: nextProps.record.visibleForms || []
        });
      }
    }
    if (showSlideFrame && !nextProps.showSlideFrame) {
      form.resetFields();
      this.setState({
        durationType: 1,
        startTime: moment('00:00', 'HH:mm'),
        endTime: moment('23:59', 'HH:mm'),
        visibleForms: []
      });
    }
  };

  onCancel = () => {
    this.props.close();
  };

  handleSave = () => {
    const { form, travelItineraryStandID, close, record } = this.props;
    const { durationType, startTime, endTime, visibleForms } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        //需要校验startTime是否在endTime之前
        if (durationType === 2 && !moment(startTime).isBefore(endTime)) {
          message.error(messages('expense-reimbursement-control.key102')/*开始时间需早于结束时间*/);
          return;
        }
        let params = {};
        params.id = record ? record.id : undefined;
        params.name = values.name;
        params.status = values.enable ? 1 : 0;
        params.durationType = durationType;
        params.startTime = moment(startTime).format('HH:mm');
        params.endTime = moment(endTime).format('HH:mm');
        params.visibleFormScope = visibleForms.length ? 2 : 1; //适用表单范围，1全部 2部分
        params.visibleForms = visibleForms;
        params.travelItineraryStandId = travelItineraryStandID;
        this.setState({loading: true});
        travelPolicyService.saveDiningScene(params).then(res => {
          this.setState({loading: false});
          close(true);
        }).catch(e => {
          this.setState({loading: false});
          errorMessage(e.response);
        });
      }
    });
  };

  handleChangeValue = (value, key) => {
    this.setState({[key]: value});
  };

  handleTimeChange = (time, type) => {
    if (type === 'start') {
      this.setState({startTime: time});
    }
    if (type === 'end') {
      this.setState({endTime: time});
    }
  };

  handleFormsChange = (values) => {
    this.setState({visibleForms: values});
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loading, durationType, startTime, endTime, visibleForms } = this.state;
    const { record, setOfBooksId, tenantMode, company } = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 10, offset: 1}
    };
    return (
      <div>
        <Form>
          <FormItem {...formItemLayout} label={messages('expense-reimbursement-control.key103')/*类型名称*/}>
            {getFieldDecorator('name', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: record ? record.name : ''
            })(
              <Input placeholder={messages('common.please.enter')} maxLength="10" />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('common.status.enable')/*启用*/}>
            {getFieldDecorator('enable', {
              valuePropName: 'checked',
              initialValue: record ? record.status === 1 : true
            })(
              <Switch checkedChildren={<Icon type="check"/>} unCheckedChildren={<Icon type="cross"/>} />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('expense-reimbursement-control.key104')/*可用时段*/}>
            <div>
              <RadioGroup value={durationType} onChange={e => this.handleChangeValue(e.target.value, 'durationType')}>
                <Radio value={1}>{messages('expense-reimbursement-control.key105')/*全天*/}</Radio>
                <Radio style={{marginLeft: 50}} value={2}>{messages('expense-reimbursement-control.key106')/*限制时段*/}</Radio>
              </RadioGroup>
              {durationType === 2 && (
                <div style={{marginTop: 12}}>
                  <TimePicker allowEmpty={false} value={startTime} format='HH:mm' onChange={time => this.handleTimeChange(time, 'start')} />
                  <TimePicker style={{marginLeft: 12}} allowEmpty={false} value={endTime} format='HH:mm' onChange={time => this.handleTimeChange(time, 'end')} />
                </div>
              )}
            </div>
          </FormItem>
          <FormItem {...formItemLayout} label={messages('expense-reimbursement-control.key107')/*适用表单设置*/}>
            <Searcher
              type="form_tenant_company"
              listExtraParams={{
                setOfBooksId: tenantMode ? setOfBooksId : company.setOfBooksId,
                companyOID: tenantMode ? undefined : company.companyOID,
                formTypeList: [2001],
                page: 0,
                size: 1000
              }}
              labelKey="formName"
              descriptionKey="companyName"
              isAll={visibleForms.length === 0}
              isShowSelectAll
              showNumber
              showClear
              value={visibleForms}
              onChange={this.handleFormsChange}
            />
          </FormItem>
        </Form>
        <div className="slide-footer">
          <Button type="primary" onClick={this.handleSave} loading={loading}>{messages('common.ok')/*确定(*/}</Button>
          <Button onClick={this.onCancel}>{messages('common.cancel')/*返回(*/}</Button>
        </div>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode,
    company: state.login.company
  }
}

NewScene.propTypes = {};

NewScene.defaultProps = {};

const WrappedNewScene = Form.create()(NewScene);

export default connect(mapStateToProps)(WrappedNewScene);
